<?php
class Scrinker
{
	const NONE            = 0;
	const MINIMIZE        = 1;
	const KEEP_LINEBREAKS = 2;
	const ALL             = 0xffff;

	private static $types = array('css' => 'Scrinker_CSS', 'js' => 'Scrinker_JS');
	public static function Get($type = null, $options = array())
	{
		if (func_get_args() == 1 and is_array($type))
		{
			$options = $type;
			$type = null;
		}

		if (is_null($type))
			return new self($options);

		if (!array_key_exists($type, self::$types))
			throw new Scrinker_Exception('Unknown type "'.$type.'"');

		return new self::$types[$type]($options);
	}
###########
	private $files = array();
	private $template, $type;
	private $basedir = '';

	protected function __construct($options = array())
	{
		$this->template = isset($options['template']) ? $options['template'] : '%s';

		if (isset($options['basedir']))
			$this->basedir = rtrim($options['basedir'], '/').'/';
	}

	public function add_file($filename)
	{
		$arguments = func_get_args();
		foreach ($arguments as $f)
			foreach ((array)$f as $filename)
			{
				if (!file_exists($filename) and !empty($this->basedir) and file_exists($this->basedir.$filename))
					$filename = $this->basedir.$filename;
				else
				{
					trigger_error('Skipping missing file "'.$filename.'"');
					continue;
				}

				array_push($this->files, $filename);
			}

		return $this;
	}

	protected function needs_combine($options, $flags)
	{
		return !file_exists($options['filename']);
	}

	protected function before_combine($options, $flags)
	{
		return '/*** Combined file - '.date('Y-m-d H:i:s').' ***/'."\n";
	}

	protected function on_combine($combined, $options, $flags)
	{
		$result  = '/* File: '.$options['filename'].' - '.date('Y-m-d H:i:s').' */'."\n";
		$result .= file_get_contents($options['filename'])."\n";

		return $result;
	}

	protected function after_combine($string, $options, $flags)
	{
		file_put_contents($options['filename'], $string);
		return $string;
	}

	protected function get_combined($options, $flags)
	{
		return $options['filename'];
	}

	public function combine($options = array(), $flags = self::MINIMIZE)
	{
		if ($this->needs_combine($options, $flags))
		{
			$contents = $this->before_combine($options, $flags);

			foreach ($this->files as $filename)
				$contents .= $this->on_combine($contents, array_merge($options, compact('filename')), $flags);

			$contents = $this->after_combine($contents, $options, $flags);
		}

		$this->files = array($this->get_combined($options, $flags));

		return $this;
	}

	/**
	 * @param  String  Prefixed path [optional]
	 * @return String  containing all generated links
	 */
	public function get_links($path = null)
	{
		if (is_null($path))
			$path = $this->basedir;
		$template = sprintf($this->template, rtrim($path, '/').'/%s');

		$result = '';
		foreach ($this->files as $asset)
			$result .= sprintf($template, basename($asset))."\n";

		return $result;
	}
}
